<?php

namespace Common\Logic;

/**
 * 管理员用户logic
 */
class AdminLogic extends BaseLogic {

    const USER_COOKIE_NAME = 'console_user_info';
    const USER_FIELD = 'id,phone,role';
    const CRYPT_KEY = 'FmL2UrsftJeF7LecaBh0V7UZHiQ7VsDN';

    private $adminModel;

    public function __construct() {
        parent::__construct();
        $this->adminModel = D('Admin');
    }

    /**
     * 获取用户登录信息
     * @return mixed
     */
    public function getUserInfo() {
        $userInfoRes = $this->getUserInfoByCookie();
        if (!static::$res->isSuc($userInfoRes)) {
            return static::$res->err("用户未登陆");
        }
        $userInfo = $userInfoRes['Result'];

        if ($userInfo['expire'] < time()) {
            return static::$res->err("登陆信息已过期");
        }

        $id = $userInfo['id'];

        $userWhere = array(
            "id" => $id,
            "state" => 1
        );

        if ($this->adminModel->where($userWhere)->count() < 1) {
            return static::$res->err("登陆信息异常");
        }

        $userInfo['expire'] = strtotime("+1 day");

        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 通过id获取用户信息
     * @param string $id
     * @return mixed
     */
    public function getUserInfoById($id) {
        if (empty($id)) {
            return static::$res->err("id不能为空");
        }
        $userWhere = array(
            "id" => $id,
            "state" => 1
        );

        $userInfo = $this->adminModel->where($userWhere)->field(static::USER_FIELD)->find();
        if (empty($userInfo)) {
            return static::$res->err("用户未注册");
        }

        $userInfo['expire'] = strtotime("+1 day");
        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 登陆账号
     * @param $phone
     * @param $password
     * @return mixed
     */
    public function login($phone, $password) {
        if (empty($phone)) {
            return static::$res->err("登陆手机不能为空");
        }
        if (!validate($phone, 'mobile')) {
            return static::$res->err("手机号格式错误");
        }
        if (empty($password)) {
            return static::$res->err("密码不能为空");
        } else {
            $password = $this->md5Password($password);
        }

        $where = array(
            "phone" => $phone,
            "password" => $password,
            "state" => 1
        );

        $userInfo = $this->adminModel->where($where)->field(static::USER_FIELD)->find();
        if (empty($userInfo)) {
            return static::$res->err("账号或密码错误");
        }

        $userInfo['expire'] = strtotime("+1 day");
        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 退出登录
     */
    public function logout(){
        cookie(static::USER_COOKIE_NAME, null);
        return static::$res->suc('成功');
    }

    /**
     * 添加用户信息返回用户信息
     * @param $userInfo
     * @return mixed
     */
    public function addUser($userInfo) {
        static $fields = array(
            "phone" => array("empty" => "用户名不能为空"),
            "password" => array("empty" => "密码不能为空"),
            "role" => array("empty" => "用户角色不能为空"),
        );

        $data = array();
        foreach ($fields as $title => $vo) {
            $val = $userInfo[$title];
            if (!empty($vo['empty'])) {
                if (empty($val)) {
                    return static::$res->err($vo['empty']);
                }
            }
            $data[$title] = $val;
        }

        if (!validate($data['phone'], 'mobile')) {
            return static::$res->err("手机号格式错误");
        }

        $where = array(
            "phone" => $data['phone'],
            "state" => 1
        );
        if($this->statistics($where)){
            return static::$res->err("手机号已存在");
        }

        $data['state'] = 1;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['password'] = $this->md5Password($data['password']);

        $id = $this->adminModel->add($data);
        if (empty($id)) {
            return static::$res->err("数据库异常，添加失败");
        }

        //添加成功，返回用户信息
        return static::$res->suc("添加成功");
    }

    /**
     * 编辑用户
     * @param $id
     * @param string $editId
     * @param array $param
     * @return mixed
     */
    public function updateUser($id, $editId, $param = array()) {
        if (empty($id)) {
            return static::$res->err("id不能为空");
        }

        if (empty($editId)) {
            return static::$res->err("编辑人不能为空");
        }

        $userWhere = array(
            "id" => $id,
            "state" => 1
        );

        unset($param['id']);
        unset($param['add_time']);
        
        $userInfoRes = $this->getInfo($userWhere);
        $userInfo = $userInfoRes['Result'];
        if(empty($userInfo)){
            return static::$res->err("未找到用户");
        }
        
        if(!empty($param['phone'])){
            if($param['phone'] != $userInfo['phone']){
                if (!validate($param['phone'], 'mobile')) {
                    return static::$res->err("手机号格式错误");
                }
                
                $count = $this->statistics(array(
                    "state"=>1,
                    "phone"=>$param['phone']
                ));
                if($count){
                    return static::$res->err("手机号已被占用");
                }
            }else{
                unset($param['phone']);
            } 
        }

        if (!empty($param['password'])) {
            $param['password'] = $this->md5Password($param['password']);
        }

        if (empty($param)) {
            return static::$res->err("没有任何改变");
        }

        $param['edit_time'] = date('Y-m-d H:i:s');
        $param['edit_id'] = $editId;

        $count = $this->adminModel->where($userWhere)->save($param);
        if (empty($count)) {
            return static::$res->err("用户没有改变");
        }

        return static::$res->suc("编辑成功");
    }

    /**
     * 管理员统计
     * @param type $where
     * @return type
     */
    public function statistics($where = array()) {
        return $this->adminModel->where($where)->count();
    }

    /**
     * 获取列表
     * @param type $page
     * @param type $size
     * @param type $where
     * @return type
     */
    public function getList($page = 1, $size = 20, $where) {
        $list = $this->adminModel->where($where)->page($page, $size)->order("id desc")->select();
        $total = $this->statistics($where);
        return static::$res->suc("成功", array(
                    "list" => $list,
                    "total" => $total
        ));
    }
    
    /**
     * 取一条数据
     * @param type $where
     * @return type
     */
    public function getInfo($where)
    {
        $info = $this->adminModel->where($where)->find();
        return static::$res->suc("成功", $info);
    }

    /**
     * 通过cookie获取登录信息
     * @return mixed
     */
    private function getUserInfoByCookie() {
        $cookieStr = cookie(static::USER_COOKIE_NAME);
        if (empty($cookieStr)) {
            return static::$res->err("登录信息不存在");
        }
        $userInfoJson = \Think\Crypt::decrypt($cookieStr, static::CRYPT_KEY);
        $userInfo = json_decode($userInfoJson, true);
        if (empty($userInfo)) {
            return static::$res->err("登录信息失效");
        }

        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 将用户信息写入到cookie
     * @param type $userInfo
     */
    private function setUserInfoToCookie($userInfo) {
        $userInfoJson = json_encode($userInfo);
        $val = \Think\Crypt::encrypt($userInfoJson, static::CRYPT_KEY);
        cookie(static::USER_COOKIE_NAME, $val);
    }

    /**
     * 加密密码
     * @param $password
     * @return string
     */
    private function md5Password($password) {
        $val = md5($password);
        return $val;
    }

}
